package edu.cmu.cs214.hw9.db.DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import edu.cmu.cs214.hw9.db.SQLiteAdapter;
import edu.cmu.cs214.hw9.resources.Constants;

/**
 * Handles looking up and inserting into the Status table.
 * @author Peter
 *
 */
public class StatusDAO extends SQLiteAdapter {

	public StatusDAO() throws Exception 
	{
		super();
	}
	
	/**
	 * Finds a status given the status's id.
	 * @param id
	 * @return
	 */
	public Status findStatus(int id)
	{
		Status ret = null;
		ResultSet rs = null;
		try 
		{
			String statement = "SELECT * FROM " + Constants.STATUSES_TABLE + " WHERE id=?;";
			PreparedStatement ps = conn.prepareStatement(statement);
			ps.setString(1, id + "");
			
			rs = ps.executeQuery();
			while(rs.next())
				ret = new Status(rs.getInt("id"), rs.getInt("user_id"), rs.getString("status"));
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		} 
		finally 
		{
            try
            {
            	if(rs != null)
            		rs.close();
            } 
            catch (SQLException e)
            {
            }
		}
		return ret;
	}
	
	/**
	 * Creates a status or notification depending on type.
	 * @param userId
	 * @param msg
	 * @param type
	 * @return true if successful, false otherwise
	 */
	private boolean create(int userId, String msg, int type)
	{
		PreparedStatement ps;
		String statement = "INSERT INTO " + Constants.STATUSES_TABLE + " (userId, status, type, date_posted) VALUES (?, ?, ?, ?)";
		try
		{
			ps = conn.prepareStatement(statement);
			ps.setInt(1, userId);
			ps.setString(2, msg);
			ps.setInt(3, type);
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			ps.setString(4, dateFormat.format(date));
			ps.executeUpdate();
		} 
		catch(SQLException e)
		{
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	/**
	 * Creates a status given the userId and status
	 * @param userId
	 * @param status
	 * @param parameterIndex 
	 * @return true if successful, false otherwise.
	 */
	public boolean createStatus(int userId, String status)
	{		
		return create(userId, status, 1);
	}
	
	/**
	 * Creates a notification given the userId and notification
	 * @param userId
	 * @param notification
	 * @return true if successful, false otherwise.
	 */
	public boolean createNotification(int userId, String notification)
	{		
		return create(userId, notification, 2);
	}
}